package com.wizardOther.Items;

import com.appclient.ClientWizardController;
import com.appclient.DaoInstanceEnum;
import com.carpark.ejb.Model.EmployeesModel;
import com.wizardOther.OtherControlledScreen;
import com.wizardOther.OtherScreensController;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Modality;
import javafx.stage.Stage;
import popup.PopupController;

/**
 *
 * @author Sawior
 */
public class EmployeeMailController implements Initializable, OtherControlledScreen {

    private OtherScreensController myController;
    @FXML
    private Label counterText;
    @FXML
    private TextField filterField;
    @FXML
    private TableView<EmployeesModel> employeeTable;
    @FXML
    private TableColumn<EmployeesModel, String> lastName;
    @FXML
    private TableColumn<EmployeesModel, String> firstName;
    @FXML
    private TableColumn<EmployeesModel, String> state;
    @FXML
    private TableColumn<EmployeesModel, String> salary;
    @FXML
    private Button send;
    @FXML
    private Button clear;
    @FXML
    private TextField topic;
    @FXML
    private HTMLEditor editor;
    @FXML
    private Button choose;
    private ObservableList<EmployeesModel> masterData = FXCollections.observableArrayList();
    private ObservableList<EmployeesModel> filteredData = FXCollections.observableArrayList();
    private Stage dialogStage;
    private ClientWizardController wizard;

    public EmployeeMailController() {
        List<EmployeesModel> data = DaoInstanceEnum.INSTANCE.getDao().getAllEmployees();
        for (EmployeesModel empl : data) {
            masterData.add(empl);
        }

        filteredData.addAll(masterData);
        masterData.addListener(new ListChangeListener<EmployeesModel>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends EmployeesModel> change) {
                updateFilteredData();
            }
        });
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        initialize();
    }

    @Override
    public void setScreenParent(OtherScreensController screenParent) {
        myController = screenParent;
    }

    @FXML
    public void sendMails(ActionEvent event) {
        if (event.getSource() == send) {
            if (editor.getHtmlText().isEmpty()) {
                createPopup("Nie wpisałeś tekstu wiadomości");
                this.editor.getStyleClass().add("textFieldWrong");
                return;
            }
            if (getSelectionList().isEmpty()) {
                createPopup("Nie wybrałeś żadnego odbiorcy wiadomości e-mail.");
                this.employeeTable.getStyleClass().add("textFieldWrong");
                return;
            }
            if (topic.getText().isEmpty()) {
                createPopup("Nie podałeś tytułu wiadomości e-mail");
                this.topic.getStyleClass().add("textFieldWrong");
                return;
            }
            markAsGood();
            clearForm();
            createPopup("Operacja powiodła się. Wysłano maili: " + getSelectionList().size());
        }
    }
    
    private ObservableList<EmployeesModel> getSelectionList() {
        return employeeTable.getSelectionModel().getSelectedItems();
    }

    private void markAsGood() {
        this.topic.getStyleClass().remove("textFieldWrong");
        this.editor.getStyleClass().remove("textFieldWrong");
        this.employeeTable.getStyleClass().remove("textFieldWrong");
    }

    @FXML
    public void clearData(ActionEvent event) {
        if (event.getSource() == clear) {
            clearForm();
        }
    }

    private void clearForm() {
        editor.setHtmlText("");
        topic.setText("");
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        lastName.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("surname"));
        firstName.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("firstname"));
        state.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("jobType"));
        salary.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("salary"));

        employeeTable.setItems(filteredData);

        filterField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                updateFilteredData();
            }
        });
        employeeTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        employeeTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                int count = getSelectionList().size();
                String text = "Wybrano: " + getSelectionList().size();
                if (count > 1) {
                    text += " użytkowników";
                } else {
                    text += " użytkownika";
                }
                counterText.setText(text);
            }
        });
    }

    /**
     * Updates the filteredData to contain all data from the masterData that
     * matches the current filter.
     */
    private void updateFilteredData() {
        filteredData.clear();

        for (EmployeesModel p : masterData) {
            if (matchesFilter(p)) {
                filteredData.add(p);
            }
        }

        // Must re-sort table after items changed
        reapplyTableSortOrder();
    }

    /**
     * Returns true if the person matches the current filter. Lower/Upper case
     * is ignored.
     *
     * @param empl
     * @return
     */
    private boolean matchesFilter(EmployeesModel empl) {
        String filterString = filterField.getText();
        if (filterString == null || filterString.isEmpty()) {
            return true;
        }
        String lowerCaseFilterString = filterString.toLowerCase();

        if (empl.getFirstname().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (empl.getSurname().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        Double salary = empl.getSalary();
        String salaryInString = "";
        if (salary != null) {
            salaryInString = salary.toString();
        }
        if (salaryInString.toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (empl.getJobType().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }

        return false;
    }

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    private void reapplyTableSortOrder() {
        ArrayList<TableColumn<EmployeesModel, ?>> sortOrder = new ArrayList<>(employeeTable.getSortOrder());
        employeeTable.getSortOrder().clear();
        employeeTable.getSortOrder().addAll(sortOrder);
    }

    @FXML
    private void makeChoice(ActionEvent event) {
        if (event.getSource() == choose) {
            Integer id = employeeTable.getSelectionModel().getSelectedItem().getEmployeeId();
            if (id != null) {
                dialogStage.close();
            }
        }
    }

    public void setWizard(ClientWizardController wizard) {
        this.wizard = wizard;
    }

    private void createPopup(String text) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("popup.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Uwaga!");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            PopupController controller = loader.getController();
            controller.setDialogStage(dialogStage);
            controller.setPopupText(text);
            dialogStage.showAndWait();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
